package com.tucc.hello.leetcode.no1_400.no1_200.no1_20.no11_20.no19;

import com.tucc.hello.leetcode.common.ListNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode node = solution.of(new int[]{1,2,3,4,5});
        solution.print(
                solution.removeNthFromEnd2(node, 5)
        );
    }

    public ListNode of(int[] nums){
        if(nums == null || nums.length == 0){
            return null;
        }
        ListNode head = new ListNode();
        head.val = nums[0];
        ListNode tail = head;
        for(int i = 1;i < nums.length;i ++){
            tail.next = new ListNode();
            tail.next.val = nums[i];
            tail = tail.next;
        }
        return head;
    }

    public void print(ListNode listNode){
        while(listNode != null){
            System.out.print(listNode.val + " ");
            listNode = listNode.next;
        }
        System.out.println();
    }

    public ListNode removeNthFromEnd2(ListNode head, int n){
        ListNode slow = head, fast = head;
        int s = n;
        while(s > 0 && fast != null){
            s --;
            fast = fast.next;
        }
        if(fast == null){
            return head.next;
        }
        ListNode preSlow = slow;
        while(fast != null){
            fast = fast.next;
            preSlow = slow;
            slow = slow.next;
        }
        preSlow.next = slow.next;
        return head;
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        List<ListNode> listNodes = new ArrayList<>();
        ListNode tail = head;
        while (tail != null) {
            listNodes.add(tail);
            tail = tail.next;
        }
        int removeIndex = listNodes.size() - n;
        if (removeIndex == 0) {
            return head.next;
        }
        listNodes.get(removeIndex - 1).next = listNodes.get(removeIndex).next;
        return head;
    }
}

